﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ChallengePuzzle.Lib
{
    public class PrimeCache
    {
        static Dictionary<int, bool> NumberDc = new Dictionary<int, bool>();

        public static bool IsPrime(int i)
        {
            if (NumberDc.ContainsKey(i)) return NumberDc[i];

            bool isPrime = IsPrimeByCaculate(i);
            
            Record(i,isPrime);
            
            return isPrime;
        }

        public static void Record(int i,bool Value)
        {
            if (!NumberDc.ContainsKey(i))
            {
                NumberDc.Add(i,Value);
            }
        }


        public static bool IsPrimeByCaculate(int Number)
        {
            int halfNumber = Number / 2;

            for (int i = 2; i < halfNumber; i++)
            {
                if (CanDiv(Number, i))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 是否能除尽
        /// </summary>
        /// <param name="Number"></param>
        /// <param name="i"></param>
        /// <returns></returns>
        private static bool CanDiv(int Number, int i)
        {
            if ((Number % i) == 0) return true;
            return false;
        }
    }
}
